package cn.yuanqiao.cqbc.util;

import cn.yuanqiao.common.core.context.ResponseUtils;
import cn.yuanqiao.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 下载文件
 *
 * @author fengshuonan
 * @Date 2019/8/7 23:14
 */
public class FileDownload {

    private static Logger log = LoggerFactory.getLogger(FileDownload.class);
    /**
     * @param response
     * @param filePath 文件完整路径(包括文件名和扩展名)
     * @param fileName 下载后看到的文件名
     * @return 文件名
     */
    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception {
        byte[] bytes = toByteArray(filePath+ File.separator+fileName);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        ResponseUtils.defaultResponse(response);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    public static byte[] toByteArray(String filename) {
        File f = new File(filename);
        if (!f.exists()) {
            log.error("文件未找到！" + filename);
            throw new ServiceException("FILE_NOT_FOUND!");
        } else {
            FileChannel channel = null;
            FileInputStream fs = null;

            try {
                fs = new FileInputStream(f);
                channel = fs.getChannel();
                ByteBuffer byteBuffer = ByteBuffer.allocate((int)channel.size());

                while(channel.read(byteBuffer) > 0) {
                }

                byte[] var5 = byteBuffer.array();
                return var5;
            } catch (IOException var17) {
                throw new ServiceException("FILE_READING_ERROR!");
            } finally {
                try {
                    channel.close();
                } catch (IOException var16) {
                    throw new ServiceException("FILE_READING_ERROR!");
                }

                try {
                    fs.close();
                } catch (IOException var15) {
                    throw new ServiceException("FILE_READING_ERROR!");
                }
            }
        }
    }

}
